import pymysql


# 连接数据库
class Database:
    def __init__(self) -> None:
        self.conn = pymysql.connect(host='127.0.0.1', port=3306, user='root',
                                    password='123', db='renren_chong', cursorclass=pymysql.cursors.DictCursor)
        # 获取游标  通过数据库获取游标
        self.cursor = self.conn.cursor()

    # 查询单个 字符串类型
    def find(self, sql):
        self.cursor.execute(sql)
        res = self.cursor.fetchone()
        return res

    # 查询所有 列表类型
    def find_all(self, sql):
        self.cursor.execute(sql)
        res = self.cursor.fetchall()
        return res

    # 添加 修改 删除
    def update(self, sql):
        self.cursor.execute(sql)
        self.conn.commit()

    def commit(self):
        self.conn.commit()

    # 关闭
    def close(self):
        self.cursor.close()
        self.conn.close()


db = Database()




# import pymysql
# import threading
#
# lock = threading.Lock()
# class DB:
#     def __init__(self) -> None:
#         self.conn = pymysql.connect(host='localhost', port=3306, user='root', password='mysql', db='userstest',
#                                     cursorclass=pymysql.cursors.DictCursor)
#         self.cursor = self.conn.cursor()
#
#     def reConnect(self):
#         try:
#             self.conn.ping()
#         except:
#             self.conn = pymysql.connect(host='localhost', port=3306, user='root', password='mysql', db='userstest',
#                                         cursorclass=pymysql.cursors.DictCursor)
#             self.cursor = self.conn.cursor()
#
#     # 更新添加
#     def update(self, sql):
#         self.cursor.execute(sql)
#
#     #     self.conn.commit()
#     #     return self.cursor.lastrowid
#
#     # 获取一条
#     def findOne(self, sql):
#         self.reConnect()
#
#         self.cursor.execute(sql)
#         res = self.cursor.fetchone()
#
#         return res
#
#     # 获取多条
#     def findAll(self, sql):
#         self.reConnect()
#         lock.acquire()
#         self.cursor.execute(sql)
#         res = self.cursor.fetchall()
#         lock.release()
#         return res
#
#     # 提交方法
#     def commit(self):
#         self.conn.commit()
#
#     # 回滚方法
#     def rollback(self):
#         self.conn.rollback()
#
#
# db = DB()
